package kr.ac.kongju.gedl.admin.service.impl;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import kr.ac.kongju.gedl.admin.service.AdminService;
import kr.ac.kongju.gedl.admin.vo.AdminInfoVO;

import org.apache.xpath.XPathAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

@Service("adminService")
public class AdminServiceImpl implements AdminService {
	
	@Autowired
    private ServletContext servletContext;
	
	
	
	public AdminInfoVO selectUser(AdminInfoVO searchVO) throws Exception{
		
		InputStream is = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getResource("WEB-INF/user.xml").getInputStream();
		
		DocumentBuilderFactory docBF = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = (DocumentBuilder) docBF.newDocumentBuilder();
		InputSource inSource = new InputSource(new InputStreamReader(is, "UTF-8"));
		Document menuDoc = docBuilder.parse(inSource);
		Element root = menuDoc.getDocumentElement();
		AdminInfoVO adminInfoVO = null;
		NodeList nodeList = XPathAPI.selectNodeList(root, "/userList/user");
		for(int i = 0; i < nodeList.getLength(); i++) {
			Node level1 = nodeList.item(i);
			String id = level1.getAttributes().getNamedItem("id").getTextContent();
			String password = level1.getAttributes().getNamedItem("password").getTextContent();
			if(id.equals(searchVO.getAdminId()) && password.equals(searchVO.getPassword())) {
				adminInfoVO = new AdminInfoVO();
				adminInfoVO.setAdminId(id);
				adminInfoVO.setPassword(password);
				adminInfoVO.setName(level1.getAttributes().getNamedItem("name").getTextContent());
				adminInfoVO.setDepartment(level1.getAttributes().getNamedItem("role").getTextContent());
			}
			
		}
		
		return adminInfoVO;
	}
	
	 

}
